package com.housekeeping.filter;

import com.housekeeping.utils.ApiResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionAuthFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        

        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        
        String requestURI = httpRequest.getRequestURI();
        

        if (isPublicPath(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        

        HttpSession session = httpRequest.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            ApiResponse.sendJsonResponse(httpRequest, httpResponse, ApiResponse.unauthorized("请先登录"));
            return;
        }
        

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private boolean isPublicPath(String requestURI) {
        return requestURI.contains("/api/auth/login") ||
               requestURI.contains("/api/auth/register") ||
               requestURI.contains("/api/public/") ||
               requestURI.endsWith(".html") ||
               requestURI.endsWith(".css") ||
               requestURI.endsWith(".js") ||
               requestURI.endsWith(".jpg") ||
               requestURI.endsWith(".png") ||
               requestURI.endsWith(".gif") ||
               requestURI.endsWith(".ico");
    }
} 